package com.dongyimai.oauth.controller;

import com.dongyimai.oauth.service.AuthService;
import com.dongyimai.oauth.util.AuthToken;
import com.offcn.entity.Result;
import com.offcn.entity.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/user")
public class AuthController {
    // 将service层对象注入
    @Autowired
    private AuthService authService;
    // 从yml配置文件中获取应用名和应用秘钥
    @Value("${auth.clientId}")
    private String clientId;

    @Value("${auth.clientSecret}")
    private String clientSecret;

    @RequestMapping("/login")
    public Result login(String username, String password, HttpServletResponse response){
        try {
            // 申请令牌、获取令牌
            AuthToken authToken = authService.login(username, password, clientId, clientSecret);
            // 并将获取的AuthToken(String accessToken, String refreshToken, String jti)存入cookie中
            Cookie cookie = new Cookie("AUTHORIZE_TOKEN", authToken.getAccessToken());
            cookie.setPath("/");
            response.addCookie(cookie);
            return new Result(true, StatusCode.OK,"登陆成功",authToken);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, StatusCode.ACCESSERROR,e.getMessage(),null);
        }
    }
}
